<h3 class="WorkflowDesignerTitleWithCreate">
  {{name}}
  {{labels.EditParameters}}
  <a v-if="!readonly" @click="add()">{{ButtonTextCreate}}</a>
</h3>
<div id="WorkflowDesignerCodeActionsParametersList" class="WorkflowDesignerWindowForm">
  <table class="WorkflowDesignerTable">
    <tr>
      <th></th>
      <th>{{ labels.Name }}</th>
      <th>{{ labels.TitleField }}</th>
      <th>
        <div>
          {{ labels.Type }}
          <el-tooltip :content="labels.CustomTypeHint" placement="right" effect="light">
            <div slot="content" style="max-width: 300px">
              {{labels.CustomTypeHint}}
              <a target="_blank" href="https://workflowengine.io/documentation/designer-customization/custom-activity#custom-form">
                {{ labels.ReadMore }}
              </a>
            </div>
            <i class="el-icon-question header-info-icon"></i>
          </el-tooltip>
        </div>
      </th>
      <th>{{ labels.IsRequired }}</th>
      <th>{{ labels.DefaultValue }}</th>
      <th>{{ showValuesLabel() ? labels.Values : '' }}</th>
    </tr>
    <tr v-for="(item, index) in items" :key="index"
        :class="dragOverIndex == index && dragOverBlock  == item ? 'dragOver' : ''"
        @dragend="dragend($event)" @dragover="dragover(item, index, $event)"
        @dragstart="dragstart(index, $event)">
      <td :draggable="!readonly" class='WorkflowDesignerTableMoveCol'>
        <div v-if="!readonly" class='WorkflowDesignerTableMoveButton'></div>
      </td>
      <td>
        <el-input v-model="item.Name" :class="validateField('Name', item) && items.length > 1? 'WorkflowDesignerInputError' : ''" :readonly="readonly" :title="items.length > 1? validateField('Name', item):''"></el-input>
      </td>
      <td>
        <el-input v-model="item.Title" :readonly="readonly"></el-input>
      </td>
      <td>
        <el-select
          v-model="item.Type" :class="validateField('Type', item) ? 'WorkflowDesignerInputError' : ''"
          :title="validateField('Type', item)" :disabled="readonly" filterable
          @change="typeOnChange(item)" allow-create
          placeholder="" style="width: 100%;">
          <el-option v-for="type in types" :key="type" :label="labels[type]" :value="type"></el-option>
        </el-select>
      </td>
      <td>
        <el-checkbox
          v-model="item.IsRequired"
          :readonly="readonly"
        ></el-checkbox>
      </td>
      <td>
        <el-input v-if="item.Type == 'Text' || item.Type == 'Json' || !types.includes(item.Type)" v-model="item.DefaultValue" :readonly="readonly"></el-input>
        <el-input-number v-if="item.Type == 'Number'" v-model="item.DefaultValue" :readonly="readonly"
                         controls-position="right"></el-input-number>
        <el-checkbox v-if="item.Type == 'Checkbox'" v-model="item.DefaultValue" :readonly="readonly"></el-checkbox>
        <el-input v-if="item.Type == 'TextArea'" v-model="item.DefaultValue" :readonly="readonly" rows="4" type="textarea">
        </el-input>

        <el-date-picker
          v-if="item.Type == 'DateTime'"
          v-model="item.DefaultValue"
          :readonly="readonly"
          type="datetime">
        </el-date-picker>
        <el-date-picker
          v-if="item.Type == 'Date'"
          v-model="item.DefaultValue"
          :readonly="readonly"
          type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker>
        <el-time-picker
          v-if="item.Type == 'Time'"
          v-model="item.DefaultValue"
          :picker-options="{
                            selectableRange: '00:00:00 - 23:59:59'
                        }"
          :readonly="readonly"
          value-format="HH:mm:ss">
        </el-time-picker>

        <el-select v-if="item.Type == 'Dropdown'" v-model="item.DefaultValue" :disabled="readonly" filterable placeholder=""
                   style="width: 100%;">
          <el-option
            v-for="item in item.DropdownValues"
            :key="item.Value"
            :label="item.Name"
            :value="item.Value">
          </el-option>
        </el-select>
        <el-select v-if="item.Type == 'MultiSelect'" v-model="item.DefaultValue" :disabled="readonly" filterable multiple placeholder=""
                   style="width: 100%;">
                    <el-option
                    v-for="v in item.DropdownValues"
                    :key="v.Value"
                    :label="v.Name"
                    :value="v.Value">
                    </el-option>
                </el-select>
            </td>
            <td v-if="!readonly" class="WorkflowDesignerTableEditButtons Double">
                <el-button-group>
          <el-button v-if="item.Type == 'Dropdown' || item.Type == 'MultiSelect' " :class="'WorkflowDesignerTableCodeParametersButton ' + (editParametersItem == item ? 'is-active' : '')"
                     @click="showDropdownValuesWindow(item)"></el-button>
          <el-button v-if="item.Type == 'Json'" :class="'WorkflowDesignerTableCodeActionsButton ' + (editItem == item ? 'is-active' : '')"
                     @click="showjson('DefaultValue', item)"></el-button>
          <el-button class="WorkflowDesignerTableDeleteButton" @click="remove(index)"></el-button>
        </el-button-group>
      </td>
    </tr>
  </table>
</div>
<div class="WorkflowDesignerButtons">
  <el-button v-if="!readonly" type="primary" @click="onSave">{{ ButtonTextSave }}</el-button>
  <el-button @click="onClose">{{ ButtonTextCancel }}</el-button>
</div>
<script type="application/javascript">
    function parametersform_Init(me){
      me.VueConfig.methods.UpdateLanguage = function () {
        me.VueConfig.data = Object.assign(me.VueConfig.data, {
          labels: {
            ReadMore: WorkflowDesignerConstants.ReadMore,
            ...WorkflowDesignerConstants.CodeActionsFormLabel
          },
          ButtonTextCreate: WorkflowDesignerConstants.ButtonTextCreate,
          ButtonTextDelete: WorkflowDesignerConstants.ButtonTextDelete,
          ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
          ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
        });
      }

      me.VueConfig.methods.UpdateLanguage();
      const types = WorkflowDesignerConstants.ParameterTypes;
      me.VueConfig.data = Object.assign(me.VueConfig.data, {
        readonly: false,
        editParametersItem: undefined,
        editItem: undefined,
        types: Object.keys(types).filter(type => type !== types.Custom)
      });

        me.VueConfig.methods.setCurrentItem = function(item) {
            this.currentItem = item;
        };

        me.VueConfig.methods.typeOnChange = function(item){
            item.DefaultValue = undefined;
        }

    me.VueConfig.methods.onUpdate = function (parentItem) {
      me.parentItem = parentItem;
      me.VueConfig.data.items = WorkflowDesignerCommon.clone(parentItem.ParameterDefinitions);
      me.VueConfig.data.items.forEach(function (item) {
        const {DefaultValue, Type} = item;
        if (Type === types.MultiSelect && typeof DefaultValue === 'string') {
          item.DefaultValue = WorkflowDesignerCommon.toJSON(DefaultValue);
        } else if (Type === types.Dropdown && DefaultValue !== null && typeof DefaultValue !== 'string') {
          item.DefaultValue = WorkflowDesignerCommon.toString(DefaultValue);
        }

        if (Type === types.Custom) {
          item.Type = item.CustomName;
        }
      });

      me.VueConfig.data.name = parentItem.Name;
      me.VueConfig.data.readonly = me.graph.Settings.readonly;
    };

    me.VueConfig.methods.add = function () {
      me.VueConfig.data.items.push({Name: '', Title: '', Type: types.Text, DropdownValues: [], IsRequired: false, DefaultValue: null});

      setTimeout(function () {
        var objDiv = document.getElementById('WorkflowDesignerCodeActionsParametersList');
        objDiv.scrollTop = objDiv.scrollHeight;
      }, 10);
    };

    me.VueConfig.methods.remove = function (index) {
      me.VueConfig.data.items.splice(index, 1);
    };

    me.VueConfig.methods.showValuesLabel = function () {
      for (var i = 0; i < me.VueConfig.data.items.length; i++) {
        if (me.VueConfig.data.items[i].Type == types.Dropdown
          || me.VueConfig.data.items[i].Type == types.MultiSelect
          || me.VueConfig.data.items[i].Type == types.Json) {
          return true;
        }
      }
      return false;
    };

    me.VueConfig.methods.showjson = function (name, item) {
      me.VueConfig.data.editItem = item;
      me.editItem = item;

      var onSuccess = function (value) {
        if (me.editItem) {
          me.editItem[name] = value;
          me.VueConfig.data.editItem = undefined;
          delete me.editItem;
        }
      };

      var onClose = function (value) {
        me.VueConfig.data.editItem = undefined;
      };

      var params = {
        name: item['Rule'],
        type: ['RuleCheck', 'RuleGet']
      };
      me.VueConfig.data.jsonform = me.showjson(item[name], params, onSuccess, onClose);
    };

    me.VueConfig.methods.validateField = function (name, item) {
      if (name != 'Name' && name != 'Type' && name != 'DefaultValue')
        return;

      if ((name != 'DefaultValue') && (!item[name])) {
        return WorkflowDesignerConstants.FieldIsRequired;
      }

      if (name == 'Name') {
        var res = me.VueConfig.data.items.filter(function (i) {
          return i != item && i.Name == item.Name
        });
        if (res.length > 0) {
          return WorkflowDesignerConstants.FieldMustBeUnique;
        }
      }

    };

    me.VueConfig.methods.validate = function () {
      var validateFunc = me.VueConfig.methods.validateField;
      var items = me.VueConfig.data.items;
      for (var i = 0; i < items.length; i++) {
        var item = items[i];

        if (validateFunc('Name', item)) {
          if (items.length > 1) {
            return false;
          }
        }

        if (validateFunc('Type', item))
          return false;

        if (validateFunc('DefaultValue', item))
          return false;
      }

      return true;
    };

    me.VueConfig.methods.onSave = function () {
      me.VueConfig.data.items.forEach(function (item) {
        const {DefaultValue, Type} = item;
        if (DefaultValue) {
          if (Type === types.Date || Type === types.Time) {
            item.DefaultValue = DefaultValue.toString();
          } else if (Type === types.DateTime) {
            item.DefaultValue = DefaultValue.toISOString();
          }
        }

        if (!Object.keys(types).includes(Type)) {
          item.CustomName = Type;
          item.Type = types.Custom;
        }
      });

      if (me.VueConfig.methods.validate && me.VueConfig.methods.validate()) {
        me.onSuccess(me.VueConfig.data.items);
        me.onClose(true);
      }
    };

    me.VueConfig.methods.onClose = function () {
      if (me.VueConfig.data.readonly) {
        me.onClose(true);
        return;
      }

            if (WorkflowDesignerCommon.compareArray(
                me.parentItem.ParameterDefinitions,
                me.VueConfig.data.items,
        ['Name', 'Title', 'Type', 'DefaultValue', 'DropdownValues', 'IsRequired'])) {

                me.onClose(true);
      } else {
        me.showConfirm();
      }
    };

    me.VueConfig.methods.onCloseSave = function () {
      me.onClose(true);
    };

    me.showConfirm = function () {
      me.VueConfig.methods.showConfirm({
        title: WorkflowDesignerConstants.DialogConfirmText,
        message: WorkflowDesignerConstants.CloseWithoutSaving,
        onSuccess: function () {
          me.VueConfig.methods.onCloseSave();
        }
      });
    }

    me.VueConfig.methods.showDropdownValuesWindow = function (item) {
      me.VueConfig.data.editParametersItem = me.editParametersItem = item;

      var windowId = me.id + '_dropdownValues';

      var onSuccess = function (res) {
        if (me.editParametersItem) {
          me.editParametersItem = WorkflowDesignerCommon.clone(res);
          me.VueConfig.data.editParametersItem = undefined;
          delete me.editParametersItem;
        }
      };

      var onClose = function () {
        if (me.editParametersItem) {
          me.VueConfig.data.editParametersItem = undefined;
          delete me.editParametersItem;
        }
      }

            if(!me.parametersform){
                var options = {
                    move: true,
                    resize: true,
                    savePosition: true,
          class: 'WorkflowDesignerDropdownValues',
                    onSuccess: onSuccess,
                    onClose: onClose,
                    parameterDefinition: {}
                };
                me.parametersform = me.graph.CreateWindow(windowId, options);
            }

      me.parametersform.show('dropdownValues', item);
    };
  }
</script>
